package isv

import (
	"dhfshop/models"
	"errors"
	"strings"
	"github.com/astaxie/beego/orm"
)

type Wxapp struct {
	AppId       int64  `orm:"column(appid);pk;auto" json:"appid" form:"appid"`                 //主键：数字类型
	AppType     int16  `orm:"column(app_type)" json:"app_type" form:"app_type"`                //类型： 1: 黄蜂商城; 2: ？
	Statu       int16  `orm:"column(statu);default(1)" json:"statu" form:"statu"`              //类型： 1: 未发布; 2: 发布？
	TemplateId  int64  `orm:"column(template_id);index" json:"template_id" form:"template_id"` //代码模板id：数字类型
	Version     string `orm:"column(version)" json:"version" form:"version"`                   //版本号：var类型
	Description string `orm:"column(description);type(text)" json:"description" form:"description"`       //版本描述：text类型
}

func (u *Wxapp) TableUnique() [][]string {
	return [][]string{
		[]string{"AppType", "TemplateId"},
	}
}

func init() {
	orm.RegisterModel(new(Wxapp))
}

// 查询
func GetWxapp(id int64) (v *Wxapp, err error) {
	o := models.GetDefaultDB()
	v = &Wxapp{AppId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// 添加
func AddWxapp(v *Wxapp) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(v)
	return
}

// 更新
func UpdateWxapp(m *Wxapp, k ...string) (err error) {
    o := models.GetDefaultDB()
	v := Wxapp{AppId: m.AppId}
	if err = o.Read(&v); err == nil {
		_, err = o.Update(m, k...)
		return
	}
	return
}

// 删除
func DeleteWxapp(id int64) (err error) {
	o := models.GetDefaultDB()
	v := Wxapp{AppId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

// 批量查询
func GetAllWxapps(query map[string]string,fields []string,order_by map[string]string,offset,limit int)([]*Wxapp, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Wxapp))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, ","); ok {
		    valueArr := strings.Split(v, ",")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}	
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*Wxapp
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

